import { JSBridge } from "../JSBridge";
import CommonUtils from "../../CommonUtils";
import ShareBase from "../ShareBase";
import QuLe from "../QuLe";
import EventManager from "../../EventManager";

export default class WeiXinShare extends ShareBase {

    private readonly successAfterSeconds = 3;

    /** 初始化，成功返回true */
    init(title: string, query: string = '') {
        super.init(title, query);
        let wx = JSBridge.getWXObj();
        if (wx) {
            let _this = this;
            wx.onShow(function (res) {
                console.log('wx.onShow:' + JSON.stringify(res), _this.onShareFinish)
                if (_this.onShareFinish) {
                    if (new Date().getTime() - _this.shareStartTime > 1000 * _this.successAfterSeconds) {
                        _this.onShareFinish(true);
                    } else {
                        _this.onShareFinish(false);
                    }
                }
            });
            wx.onHide(function (res) {
                console.log('wx.onHide:' + (JSON.stringify(res)))
            });
            wx.onAudioInterruptionBegin(function () {
                console.log('wx.onAudioInterruptionBegin()')
            });
            wx.onAudioInterruptionEnd(function () {
                console.log('wx.onAudioInterruptionEnd()')
            });

            //激活被动分享
            this.activePassiveShare(title, query);
        }
    }

    /**
     * 分享
     * @param query "nick=aaa&gender=0"
     * @param onShareFinish 根据才做时间判断，3秒或以上返回true，小于3秒返回false
     */
    share(title: string, query: string = '', onShareFinish?: Function): void {
        super.share(title, query, onShareFinish);
        let wx = JSBridge.getWXObj();
        if (!wx) return;
        let imgs = QuLe.instance.remoteConfig.shareImgs;
        let ShareImg = imgs[CommonUtils.randomInt(0, imgs.length)];
        wx.shareAppMessage({ title: title, imageUrl: ShareImg.url, imageUrlId: ShareImg.id, query: query });
    }

    /** 激活被动分享（点击右上角的菜单，在弹出框中点击按钮“发送给朋友”，不激活是不会出现这个按钮的） */
    private activePassiveShare(title: string, query: string = ''): void {
        let wx = JSBridge.getWXObj();
        if (!wx) return;
        wx.showShareMenu({ withShareTicket: true });
        let imgs = QuLe.instance.remoteConfig.shareImgs;
        let ShareImg = imgs[CommonUtils.randomInt(0, imgs.length)];
        wx.onShareAppMessage(function () {
            return {
                title: title,
                imageUrl: ShareImg.url,
                imageUrlId: ShareImg.id,
                query: query,
                success: (res) => {
                    console.log('右上角分享成功：' + res);
                },
                fail: (err) => {
                    console.log('右上角分享失败：' + err);
                }
            }
        });
    }

}
